import pandas as pd
import matplotlib.pyplot as plt

# 配置常量
DATA_FILE = 'd:/民大实训/git-mcp-test/project/练习一/FhjlViewDD.xlsx'
OUTPUT_IMAGE = '6月份前十个车牌号总货运量箱状图.png'
VEHICLE_COLUMN = '车辆'
FREIGHT_COLUMN = '净重'
DPI = 300
FIG_SIZE = (12, 10)
TITLE = '6月份前十个车牌号的总货运量箱状图'
TOP_N = 10

# 设置图片清晰度和中文字体
plt.rcParams['figure.dpi'] = DPI
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


def load_data(file_path: str) -> pd.DataFrame:
    """加载数据文件"""
    try:
        return pd.read_excel(file_path)
    except FileNotFoundError:
        print(f'错误：未找到文件 {file_path}，请检查文件路径。')
        return pd.DataFrame()
    except Exception as e:
        print(f'发生未知错误：{e}')
        return pd.DataFrame()


def calculate_total_freight(df: pd.DataFrame) -> pd.Series:
    """计算各车辆的总货运量"""
    return df.groupby(VEHICLE_COLUMN)[FREIGHT_COLUMN].sum()


def get_top_n_vehicles(data: pd.Series, n: int) -> pd.Series:
    """获取总货运量前 n 的车辆"""
    return data.sort_values(ascending=False).head(n)


def plot_box_chart(data: pd.Series) -> plt.Figure:
    """绘制箱状图"""
    fig = plt.figure(figsize=FIG_SIZE)
    data.plot.box()
    plt.title(TITLE)
    plt.ylabel('总货运量')
    plt.tight_layout()
    return fig


def save_chart(fig: plt.Figure, output_path: str) -> None:
    """保存箱状图"""
    fig.savefig(output_path)
    print(f'箱状图已成功保存为 {output_path}')


def main() -> None:
    """主函数"""
    df = load_data(DATA_FILE)
    if not df.empty:
        totals = calculate_total_freight(df)
        top_n_totals = get_top_n_vehicles(totals, TOP_N)
        fig = plot_box_chart(top_n_totals)
        save_chart(fig, OUTPUT_IMAGE)


if __name__ == '__main__':
    main()